<template>
  <div class="adddata">
    <div class="header">
      <div class="left">
        <span>作物：</span>
        <span>{{ cropName }}</span>
      </div>
      <div class="right">
        <el-button type="primary" size="small" icon="el-icon-arrow-left" @click="goback">返回</el-button>
        <el-button type="primary" size="small" icon="el-icon-message" @click="save">保存</el-button>
      </div>
    </div>
    <div class="line" />
    <div class="content">
      <el-table
        v-loading="listLoading"
        stripe
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column width="180">
          <template slot="header">
            <el-button icon="el-icon-plus" circle @click="addRow" />
          </template>
          <template slot-scope="scope">
            <el-button icon="el-icon-plus" circle @click="addRow" />
            <el-button icon="el-icon-minus" circle @click="deleteRow(scope.$index)" />
          </template>
        </el-table-column>
        <el-table-column label="属性" width="180">
          <template slot-scope="scope">
            <el-select v-model="tableData[scope.$index].cropProperty" placeholder="请选择">
              <el-option
                v-for="item in propOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="检测时间" width="200">
          <template slot-scope="scope">
            <el-date-picker
              v-model="tableData[scope.$index].detectionTime"
              style="width:160px"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
            />
          </template>
        </el-table-column>
        <el-table-column label="生育期" width="180">
          <template slot-scope="scope">
            <el-select v-model="tableData[scope.$index].growthPeriod" placeholder="请选择">
              <el-option
                v-for="item in durationOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="处理" width="180">
          <template slot-scope="scope">
            <el-input v-model="tableData[scope.$index].process" />
          </template>
        </el-table-column>
        <el-table-column v-for="(item,index) in extraParam" :key="index+'extra'" :label="item" width="180">
          <template slot-scope="scope">
            <el-input v-model="tableData[scope.$index].extraParam[`${item}`]" @click="changeInput(tableData[scope.$index].extraParam[`${item}`])" />
          </template>
        </el-table-column>
        <el-table-column width="180">
          <template slot="header">
            <span style="margin-right:4%">数据1</span>
            <el-button icon="el-icon-plus" circle size="mini" @click="addProp" />
          </template>
          <template slot-scope="scope">
            <el-input v-model="tableData[scope.$index].data[0]" />
          </template>
        </el-table-column>
        <el-table-column v-for="(item,index) in propTotal" :key="index+'prop'" width="180">
          <template slot="header">
            <span style="margin-right:4%">{{ item }}</span>
            <el-button icon="el-icon-plus" circle size="mini" @click="addProp" />
            <el-button icon="el-icon-minus" circle size="mini" @click="deleteProp(index)" />
          </template>
          <template slot-scope="scope">
            <el-input v-model="tableData[scope.$index].data[index+1]" />
          </template>
        </el-table-column>
        <el-table-column width="180" label="平均数">
          <template slot-scope="scope">
            <div class="column" @click="getAverage(scope.$index)">{{ ' '+tableData[scope.$index].average }}</div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { getCropProperty, getCropGrowthPeriod, getCropParams, addData } from '@/api/Crop'
import { getDataReport, updateDataReport } from '@/api/dataReport'
export default {
  name: 'Adddata',
  data() {
    return {
      listLoading: true,
      role: '',
      cropId: '',
      cropName: '',
      id: '',
      dataReportId: '',
      studentId: '',
      propTotal: [], // 数据属性总和
      extraParam: [],
      propOptions: [],
      durationOptions: [],
      templateData: {
        cropProperty: '',
        detectionTime: '',
        growthPeriod: '',
        process: '',
        extraParam: {},
        data: [],
        average: ''
      },
      tableData: [{
        cropProperty: '',
        detectionTime: '',
        growthPeriod: '',
        process: '',
        extraParam: {},
        data: [],
        average: ''
      }]
    }
  },
  created() {
    this.role = this.$store.getters.roles[0]
    this.cropName = this.$store.getters.cropName
    this.studentId = this.$store.getters.id
    this.cropId = this.$route.query.data.cropId
    this.dataReportId = this.$route.query.data.dataReportId
    const data = {
      cropId: this.cropId
    }
    this.getCropParameter(data)
    this.getCropProperty(data)
    this.getCropGrowthPeriod(data)
    const cropdata = {
      dataReportId: this.dataReportId
    }
    this.getDataReport(cropdata)
  },
  methods: {
    goback() {
      this.$router.go(-1)
    },
    addProp() { // 添加属性
      const length = this.propTotal.length
      this.propTotal.splice(length, 0, `数据${length + 2}`)
    },
    deleteProp(index) { // 删除属性
      console.log(index)
      const length = this.propTotal.length
      this.propTotal.splice(length - 1, 1)
      for (let i = 0; i < this.tableData.length; i++) {
        this.tableData[i].data.splice(index + 1, 1)// index为除了数据1外的，其他数据的下标，从0开始
      }
    },
    addRow() { // 添加行
      const length = this.tableData.length
      const obj = {}
      for (const key in this.templateData) {
        if(typeof this.templateData[key] == "object"){
          let tmp = JSON.stringify(this.templateData[key]);
          obj[key] = JSON.parse(tmp);
        }else{
          obj[key] = this.templateData[key]
        }
      }
      // obj.data.length = this.templateData.data.length;
      this.tableData.splice(length, 0, obj)
    },
    deleteRow(index) { // 删除行,index为删除的第几行，从0开始
      this.tableData.splice(index, 1)
    },
    save() { // 点击保存时触发
      console.log(this.tableData)
      console.log(this.extraParam)
      const data = {
        cropDatas: this.tableData,
        cropId: this.cropId,
        studentId: this.studentId,
        id: this.id,
        dataReportId: this.dataReportId
      }
      updateDataReport(data).then(res => {
        console.log(res)
        this.$message({
          type: 'success',
          message: '保存成功!'
        })
      })
    },
    getCropParameter(data) { // 获取作物中的所有参数
      getCropParams(data).then(res => {
        if (res.data.length > 4) {
          const extra = res.data.slice(4)
          for (let i = 0; i < extra.length; i++) {
            const parameterName = extra[i].parameterName
            this.extraParam.push(parameterName)
            for (let j = 0; j < this.tableData.length; j++) {
              this.$set(this.tableData[j].extraParam, `${parameterName}`, '')
              // this.tableData[j].extraParam[parameterName] = '';
            }
            this.$set(this.templateData.extraParam, `${parameterName}`, '')
            // this.templateData.extraParam[parameterName] = '';
            console.log(this.templateData)
          }
        }
      })
    },
    getCropProperty(data) { // 获得名叫属性的参数中的所有属性
      getCropProperty(data).then(res => {
        for (let i = 0; i < res.data.length; i++) {
          this.propOptions.push({
            value: `${res.data[i].propertyName}`,
            label: `${res.data[i].propertyName}`
          })
        }
        console.log(this.propOptions)
      })
    },
    getCropGrowthPeriod(data) { // 获得生育期中的所有属性
      getCropGrowthPeriod(data).then(res => {
        for (let i = 0; i < res.data.length; i++) {
          this.durationOptions.push({
            value: `${res.data[i].growthPeriodName}`,
            label: `${res.data[i].growthPeriodName}`
          })
        }
      })
    },
    getAverage(index) {
      console.log('okk')
      const data = this.tableData[index].data
      let sum = 0
      for (let i = 0; i < data.length; i++) {
        sum += parseFloat(data[i])
      }
      if (data.length > 0) {
        this.$set(this.tableData[index], 'average', sum / data.length)
      }
    },
    getDataReport(data) {
      getDataReport(data).then(res => {
        this.id = res.data.id
        this.tableData = res.data.cropDatas
        if (this.tableData.length && this.tableData[0].data.length) {
          for (let i = 1; i < this.tableData[0].data.length; i++) {
            this.propTotal.push(`数据${i + 1}`)
          }
        }
        this.listLoading = false
      })
    }
  }
}
</script>
<style scoped>
    .header{
        display: flex;
        justify-content: space-between;
        margin-bottom: 1%;
    }
    .left{
        color: #345E8F;
        font-size: 16px;
    }
    .line{
      width: 100%;
      border: 1px solid #F2F2F2;
    }
    .column{
      width: 180px;
      height: 57.67px;
      text-align: center;
      line-height: 57.67px;
    }
</style>
